<?php

namespace app\admin\controller\routine;
use app\admin\model\Module;
use app\common\controller\Backend;

/**
 * 页面模块
 */
class PageModule extends Backend
{
    /**
     * PageModule模型对象
     * @var object
     * @phpstan-var \app\admin\model\PageModule
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id'];

    protected string|array $quickSearchField = ['id','api_url'];

    protected array $withJoinTable = ['shop'=>['name'],'pagepath'=>['title','path']];


    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\PageModule();
    }




    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */

      /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $arr = $res->items();
        foreach($arr as &$v){ 
              if($v['page_module_ids']){
                  $all_module = Module::whereIn("id",explode(",",$v['page_module_ids']))->column("marks");
                  $v['modules'] = implode(",",$all_module);
              }
             
        }
        $this->success('', [    
            'list'   => $arr,
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }


     /**
     * 添加
     */
    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }else{
                if(isset($data['page_module_ids'])){
                     if($data['type'] == 1 && count($data['page_module_ids']) != 1){
                          $this->error("该类型下，只能关联一个模块");
                     }
                     $data['page_module_ids'] = implode(",",$data['page_module_ids']);
                }

            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                if(isset($data['methods'])){
                     $data['methods'] = implode(",",$data['methods']);
                }
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }


    /**
     * 编辑
     * @throws Throwable
     */
    public function edit(): void
    {
        $pk  = $this->model->getPk();
        $id  = $this->request->param($pk);
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }else{
             if($row['page_module_ids']){
                  $row['page_module_ids'] = explode(",",$row['page_module_ids']);
             }
             if($row['methods']){
                  $md = explode(",",$row['methods']);
                  $md2 = array_filter($md);
                  $row['methods'] = $md2;
             }
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }else{
                 if(isset($data['page_module_ids'])){
                     $data['page_module_ids'] = implode(",",$data['page_module_ids']);
                 }
            }

            $data   = $this->excludeFields($data);
            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate();
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $data[$pk] = $row[$pk];
                        $validate->check($data);
                    }
                }
                if(isset($data['methods'])){
                     $dm = array_filter($data['methods']);
                     $data['methods'] = implode(",",$dm);
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $this->success('', [
            'row' => $row
        ]);
    }



}